import requestV2 from '@/utils/requestV2' // web 和 uniapp request 不同，各自放到 utils/requestV2
import { Definition } from '../engine/common/definition.js'
import { Engine } from '../engine/engine.js'
import { Util } from '../utils/util.js'
import { DocType } from '../engine/common/docDefinition.js'
import networkCache from "./networkCache.js";
import { InventoryInOutType } from "../engine/inventory/inventory";

// 获取平台版本配置信息
export const requestBackendConfigData = () => {
	//return request('/dapi/settings/base', 'GET', null, false, true)
	return requestV2({
		url: '/api/settings/base',
		method: 'GET',
		data: null,
		loading: false,
		isPlatformReq: true,
		enableCache: false
	})
}

// 获取device id
export const getDeviceId = () => {
	//return request('getDeviceOnlyId', 'GET', null, false)
	return requestV2({
		url: 'getDeviceOnlyId',
		method: 'GET',
		data: null,
		loading: false,
		enableCache: false
	})
}


// 登录
export const login = (params) => {
	//return request('/merchant/login', 'POST', params)
	return requestV2({
		url: 'merchant/login',
		method: 'POST',
		data: params,
		enableCache: false
	})
}


// 获取device id
export const getAccountOrgJoinData = (orgId, accountId) => {
	//return request('getOrgAccJoinInfo?orgId=' + orgId + '&accountId=' + accountId, 'GET', null, false)
	return requestV2({
		url: 'getOrgAccJoinInfo?orgId=' + orgId + '&accountId=' + accountId,
		method: 'GET',
		data: null,
		loading: false,
		enableCache: false
	})
}


// 获取商户详情
export const getMerchantOrgActivePackageInfo = (orgId) => {

	let param = { "orgId": orgId }
	return requestV2({
		url: 'getMerchantOrgActivePkgInfo',
		method: 'GET',
		data: param,
		loading: false,
		enableCache: false
	})

}

/// 获取公共门店
export const getPublicStore = (orgId) => {
	let param = { "orgId": orgId }
	/*
	return request('getMerchantPublicStore', 'POST', param, false, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
		*/
	return requestV2({
		url: 'getMerchantPublicStore',
		method: 'POST',
		data: param,
		loading: false,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		enableCache: false
	})
}

/// 获取商户配置
export const getOrgSettings = (orgId) => {
	let param = { "merchantOrgSettingsId": orgId }
	/*
	return request('getMerchantOrgSettingsInfoSingleById', 'POST', param, false, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
	*/
	return requestV2({
		url: 'getMerchantOrgSettingsInfoSingleById',
		method: 'POST',
		data: param,
		loading: false,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		enableCache: false
	})
}

/// 获取商户零售配置
export const getRetailSettings = (orgId) => {
	let param = { "merchantRetailSettingsId": orgId }
	/*
	return request('getMerchantRetailSettingsInfoSingleById', 'POST', param, false, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
		*/
	return requestV2({
		url: 'getMerchantRetailSettingsInfoSingleById',
		method: 'POST',
		data: param,
		loading: false,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		enableCache: false
	})
}

/// 获取门店列表(所有门店)
export const getAllStoreList = (orgId, filter) => {
	param = { "orgId": orgId, };

	if (filter != null) {
		filter.forEach((key, value) => {
			param[key] = value;
		});
	}

	//	return request('getMerchantStoreInfoList', 'GET', param, false)
	return requestV2({
		url: 'getMerchantStoreInfoList',
		method: 'GET',
		data: param,
		loading: false,
	})
}

/// 清除基本单位缓存
export const deleteCommodityUnitNetworkCache = () => {
	networkCache.clearByApi('getMerchantUnitOrgJoinListByPage');
}

/// 获取基本单位
export const getCommodityUnit =
	({ orgId, pageInfo, filter = null, showLoading = true }) => {
		let param = {
			"orgId": orgId,
		}

		param['pageSize'] = pageInfo.limitPerPage;
		param['pageNum'] = pageInfo.curIndex;

		// 判断 filter 是否为空对象
		if (filter && Object.keys(filter).length > 0) {
			// 如果 filter 有内容，遍历其键值对
			for (let [key, value] of Object.entries(filter)) {
				param[key] = value;
			}
		}
		//return request('getMerchantUnitOrgJoinListByPage', 'GET', param, showLoading)
		return requestV2({
			url: 'getMerchantUnitOrgJoinListByPage',
			method: 'GET',
			data: param,
			loading: showLoading,
		})
	}


/// 创建基本单位
export const createCommodityUnit = (unitName, supportDecimal, orgId) => {
	deleteCommodityUnitNetworkCache();
	let param = {
		'orgId': orgId,
		'name': unitName,
		"decimalSupport": supportDecimal ? 1 : 0
	}
	//return request('addMerchantUnitOrgJoins', 'POST', param, true)
	return requestV2({
		url: 'addMerchantUnitOrgJoins',
		method: 'POST',
		data: param,
		loading: true,
	})
}

/// 修改基础单位
export const updateCommodityUnit = (unitId, unitName, supportDecimal, orgId) => {
	deleteCommodityUnitNetworkCache();
	let param = {
		'orgId': orgId,
		'id': unitId,
		'name': unitName,
		"decimalSupport": supportDecimal ? 1 : 0
	}
	//return request('modMerchantUnitOrgJoin', 'POST', param, true)
	return requestV2({
		url: 'modMerchantUnitOrgJoin',
		method: 'POST',
		data: param,
		loading: true,
	})
}


/// 删除基本单位
export const delCommodityUnit = (unitId, orgId) => {
	deleteCommodityUnitNetworkCache();
	let param = { 'merchantUnitOrgJoinIds': unitId, "orgId": orgId }

	return requestV2({
		url: 'delMerchantUnitOrgJoin',
		method: 'POST',
		data: param,
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	})
}

export const deleteCommodityKindNetworkCache = () => {
	networkCache.clearByApi('getCommodityCategoryInfoListByPage');
}

export const getCommodityCategory =
	({ orgId, pageInfo, filter = null, showLoading = false }) => {
		let param = {
			"orgId": orgId,
		};
		// 合并 filter
		if (filter && Object.keys(filter).length > 0) {
			for (let [key, value] of Object.entries(filter)) {
				param[key] = value;
			}
		}
		// 分页参数
		param['pageSize'] = pageInfo.limitPerPage;
		param['pageNum'] = pageInfo.curIndex;

		//return request('getCommodityCategoryInfoListByPage', 'GET', param, showLoading);
		return requestV2({
			url: 'getCommodityCategoryInfoListByPage',
			method: 'GET',
			data: param,
			loading: showLoading,
			enableCache: true
		})
	}

/// 创建商品类别
export const createCommodityCategory = (categoryName, orgId) => {
	deleteCommodityKindNetworkCache();
	let param = {
		'orgId': orgId,
		'categoryName': categoryName
	}
	//return request('addCommodityCategoryInfos', 'POST', param, true)
	return requestV2({
		url: 'addCommodityCategoryInfos',
		method: 'POST',
		data: param,
		loading: true,
	})
}

/// 修改商品类别
export const updateCommodityCategory = (categoryId, categoryName, orgId) => {
	deleteCommodityKindNetworkCache();
	let param = {
		'orgId': orgId,
		'id': categoryId,
		'categoryName': categoryName
	}
	//return request('modCommodityCategoryInfo', 'POST', param, true)
	return requestV2({
		url: 'modCommodityCategoryInfo',
		method: 'POST',
		data: param,
		loading: true,
	})
}

/// 删除商品类别
export const delCommodityCategory = (categoryId, orgId) => {
	deleteCommodityKindNetworkCache();
	let param = {
		'commodityCategoryInfoIds': categoryId,
		'orgId': orgId
	}
	/*
	return request('delCommodityCategoryInfo', 'POST', param, true, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
	*/
	return requestV2({
		url: 'delCommodityCategoryInfo',
		method: 'POST',
		data: param,
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	})
}

/// 商品信息缓存
const deleteCommodityNetworkCache = () => {
	networkCache.clearByApi('getMerchantCommodityInfoListByPage');
	networkCache.clearByApi('getMerchantCommodityInfoListByPageV2');
	networkCache.clearByApi('getCommoditySpecInfoListByPage');
	deleteSubCommoditySumDataCache();
}

/// 获取商品规格列表
export const getCommoditySpecList =
	({ orgId, pageInfo, filter = null, showLoading = true }) => {
		let param = {
			"orgId": orgId,
		};

		// 合并 filter
		if (filter && Object.keys(filter).length > 0) {
			for (let [key, value] of Object.entries(filter)) {
				param[key] = value;
			}
		}
		// 分页参数
		param['pageSize'] = pageInfo.limitPerPage;
		param['pageNum'] = pageInfo.curIndex;

		return requestV2({
			url: 'getCommoditySpecInfoListByPage',
			method: 'GET',
			data: param,
			loading: showLoading,
			enableCache: true,
		})
	}

/// 获取商品信息
/// 返回商品信息和商品数量(该商品下所有规格商品数量)
export const getCommodityDataV2 =
	({ orgId, pageInfo, filter = null, showLoading = true }) => {
		let param = {
			"createOrg": orgId,
		};

		// 合并 filter
		if (filter && Object.keys(filter).length > 0) {
			for (let [key, value] of Object.entries(filter)) {
				param[key] = value;
			}
		}
		// 分页参数
		param['pageSize'] = pageInfo.limitPerPage;
		param['pageNum'] = pageInfo.curIndex;

		//return request('getMerchantCommodityInfoListByPageV2', 'GET', param, showLoading);
		return requestV2({
			url: 'getMerchantCommodityInfoListByPageV2',
			method: 'GET',
			data: param,
			loading: showLoading,
		})
	}

/// 获取商品信息
/// 返回商品信息和商品数量(该商品下所有规格商品数量)
export const getCommodityData = ({ orgId, pageInfo, filter = null, showLoading = false }) => {
	let param = {
		"createOrg": orgId,
	};

	// 合并 filter
	if (filter && Object.keys(filter).length > 0) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}
	// 分页参数
	param['pageSize'] = pageInfo.limitPerPage;
	param['pageNum'] = pageInfo.curIndex;

	//return request('getMerchantCommodityInfoListByPage', 'GET', param, showLoading);
	return requestV2({
		url: 'getMerchantCommodityInfoListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
	})

}

/// 新建或更新商品信息
export const getCommodityDetailInfo = (commodityId, orgId) => {
	let param = {
		'merchantCommodityInfoId': commodityId,
		'orgId': orgId
	}
	/*
	return request('getMerchantCommodityInfoSingleById', 'POST', param, true, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
	*/
	return requestV2({
		url: 'getMerchantCommodityInfoSingleById',
		method: 'POST',
		data: param,
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	})

}

/// 删除商品类别
export const removeCommodity = (idList) => {
	deleteCommodityNetworkCache();
	let param = {
		'merchantCommodityInfoIds': idList,
	}
	/*
	return request('delMerchantCommodityInfo', 'POST', param, true, false, {
		'Content-Type': 'application/x-www-form-urlencoded',
	})
		*/
	return requestV2({
		url: 'delMerchantCommodityInfo',
		method: 'POST',
		data: param,
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	})
}

/// 创建或更新商品
export const updateOrCreateCommodiy = (commodity) => {
	deleteCommodityNetworkCache();
	let api = Util.isEmpty(commodity.id)
		? "addMerchantCommodityInfos"
		: "modMerchantCommodityInfo";

	let param = commodity.toJson();
	//return request(api, 'POST', param);
	return requestV2({
		url: api,
		method: 'POST',
		data: param,
	})
}



///
/// 创建或更新子商品信息
export const updateOrCreateSubCommodiy = (subCommodity) => {
	deleteCommodityNetworkCache();
	let api = subCommodity.id.isEmpty
		? "modCommoditySpecInfo"
		: "modMerchantCommodityInfo";

	let param = subCommodity.toJson();
	//return request(api, 'POST', param);
	return requestV2({
		url: api,
		method: 'POST',
		data: param,
	})
}

/// 更新商品成本
export const updateSubCommodityCost = (subCommodity, orgId, updateUser) => {
	let param = {
		"commodityId": subCommodity.commodityId,
		"specId": subCommodity.id,
		"costPrice": subCommodity.cost.value,
		"orgId": orgId,
		"updateName": updateUser,
	};
	//return request("modMerchantCommodityCost", 'POST', param);
	return requestV2({
		url: "modMerchantCommodityCost",
		method: 'POST',
		data: param,
	})
}

/// 清除仓库单位缓存
export const deleteWarehouseNetworkCache = () => {
	networkCache.clearByApi('getMerchantStorageInfoListByPage');
}

/// 获取仓库列表
export const getWarehouseData =
	({ orgId, pageInfo, filter = null, showLoading = true }) => {
		let param = {
			"orgId": orgId,
			"pageSize": pageInfo.limitPerPage,
			"pageNum": pageInfo.curIndex,
		}

		if (filter && Object.keys(filter).length > 0) {
			// 如果 filter 有内容，遍历其键值对
			for (let [key, value] of Object.entries(filter)) {
				param[key] = value;
			}
		}

		//return request('getMerchantStorageInfoListByPage', 'GET', param, showLoading);
		return requestV2({
			url: 'getMerchantStorageInfoListByPage',
			method: 'GET',
			data: param,
			loading: showLoading,
			enableCache: true,
		})
	}

/// 获取仓库详情

export const getWarehouseDetail = (warehouseId, orgId) => {

	let param = {
		merchantStorageInfoId: warehouseId,
		orgId: orgId,
	}

	return requestV2({
		url: 'getMerchantStorageInfoSingleById',
		method: 'post',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',  // FormData.fromMap(param)
		},
	})
}


/// 新建或更新仓库信息
export const updateOrCreateWareHouse = ({
	wareHouse,
}) => {
	// 增删改清除缓存
	deleteWarehouseNetworkCache();

	let api = Util.isEmpty(wareHouse.id) ? 'addMerchantStorageInfos' : 'modMerchantStorageInfo';

	return requestV2({
		url: api,
		method: 'POST',
		data: wareHouse.toJson(),
		loading: true,
	})
}

/// 删除仓库
export const removeWareHouse = ({ ids, orgId }) => {
	// 增删改清除缓存
	deleteWarehouseNetworkCache();

	return requestV2({
		url: 'delMerchantStorageInfo',
		method: 'POST',
		data: {
			merchantStorageInfoIds: ids,
			orgId: orgId,
		},
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',  // FormData.fromMap(param)
		},
	})
}

/// Clear target object cache
export const deleteTargetObjectNetworkCache = () => {
	networkCache.clearByApi('getMerchantCustomerInfoListByPage');
}

/**
 * 获取客户信息
 * @param {string} orgId - 组织ID
 * @param {Object} pageInfo - 分页信息 {limitPerPage: number, curIndex: number}
 * @param {Object} [filter] - 过滤条件
 * @returns {Promise<ApiReturnStruct>}
 */
export const getTargetObjectData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		orgId: orgId,
		//	customerType: 0, // 0: customer, 1: supplier
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	//console.log(" api getTargetObjectData param:", param);

	return requestV2({
		url: 'getMerchantCustomerInfoListByPage',
		method: 'GET',
		data: param,
		enableCache: false   // 关闭缓存，因为会获取往来单位的资金账户信息，所以不能缓存，保障拿到最新数据
	});
}

/// Create/update supplier
export const updateOrCreateSupplier = (supplier) => {
	deleteTargetObjectNetworkCache();

	const api = Util.isEmpty(supplier.id)
		? "addMerchantCustomerInfos"
		: "modMerchantCustomerInfo";

	return requestV2({
		url: api,
		method: 'POST',
		data: supplier.toJson(),
		loading: true
	});
}

/// Get supplier list
export const getSupplierData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		orgId: orgId,
		customerType: 1, // 0: customer, 1: supplier
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantCustomerInfoListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
}

/// Get supplier detail
export const getTargetObjectDetailInfo = (id, orgId, storeId = null) => {
	const param = {
		merchantCustomerInfoId: id,
		orgId: orgId
	};

	if (storeId) {
		param.storeId = storeId;
	}

	return requestV2({
		url: 'getMerchantCustomerInfoSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		}
	});
}

/// Delete supplier
export const removeSupplier = (ids) => {
	deleteTargetObjectNetworkCache();

	return requestV2({
		url: 'delMerchantCustomerInfo',
		method: 'POST',
		data: {
			merchantCustomerInfoIds: ids
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}

/// Create/update customer
export const updateOrCreateCustomer = (customer) => {
	deleteTargetObjectNetworkCache();

	const api = Util.isEmpty(customer.id)
		? "addMerchantCustomerInfos"
		: "modMerchantCustomerInfo";

	return requestV2({
		url: api,
		method: 'POST',
		data: customer.toJson(),
		loading: true
	});
}

/// Get customer list
export const getCustomerData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		orgId: orgId,
		customerType: 0, // 0: customer, 1: supplier
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantCustomerInfoListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
}

// 修改客户快捷扩展字段
export const updateCustomerQuickExtention = ({id,orgId,quickExtentionFields}) => {
	deleteTargetObjectNetworkCache();

	const api = "modMerchantCustomerInfo";

	return requestV2({
		url: api,
		method: 'POST',
		data: {
			id:id,
			orgId:orgId,
			quickExtentionFields:quickExtentionFields
		},
		loading: true
	});
}

/// Delete customer
export const removeCustomer = (ids) => {
	deleteTargetObjectNetworkCache();

	return requestV2({
		url: 'delMerchantCustomerInfo',
		method: 'POST',
		data: {
			merchantCustomerInfoIds: ids
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}

/// 删除所有用户应收列表缓存
export const deleteAllTargetObjectPendingReceiveNetworkCacheData = () => {
	networkCache.clearByApi('getWaitReceiptIndexPage');
}

/// 系统对象待支付资金信息
/// 按资金排序
export const getAllTargetObjectPendingReceiveData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		orgId: orgId,
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getWaitReceiptIndexPage',
		method: 'GET',
		data: param,
		enableCache: true
	});
}

///////////////////////////  资金相关接口
/// 删除所有用户应付列表缓存
export const deleteAllTargetObjectPendingPaymentNetworkCacheData = () => {
	networkCache.clearByApi('getWaitPaymentIndexPage');
}

/// 系统对象待支付资金信息
export const getAllTargetObjectPendingPaymentData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		orgId: orgId,
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getWaitPaymentIndexPage',
		method: 'GET',
		data: param,
		enableCache: true
	});
}

// 删除出入库单缓存
export const deleteInventoryNetworkCache = () => {
	networkCache.clearByApi("getMerchantInoutOrderListByPage");
}

// 获取入库单列表信息
export const getInventoryBatchData = ({ orgId, pageInfo, filter = null, showLoading = true }) => {
	let param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantInoutOrderListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	});
}

// 获取入库单详情信息
export const getInventoryBatchDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantInoutOrderId": id,
	};

	return requestV2({
		url: 'getMerchantInoutOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}

// 新建或更新商品信息
export const updateOrCreateInventoryBatch = (inventory, toAudit) => {
	deleteInventoryNetworkCache();

	const api = Util.isEmpty(inventory.id)
		? 'addMerchantInoutOrders'
		: 'modMerchantInoutOrder';

	const param = inventory.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
}

// 删除入库记录 (暂时不用这个接口)
/*
export const removeInventory = (idList, orgId) => {
	deleteInventoryNetworkCache();

	return requestV2({
		url: 'delMerchantInoutOrder',
		method: 'POST',
		data: {
			merchantInoutOrderIds: idList,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}
	*/

// 审核入库记录 idList 逗号区分多条记录
export const reviewInventory = (idList, orgId) => {
	deleteInventoryNetworkCache();
	//deleteSubCommoditySumDataCache();

	const param = {
		ids: idList,
		orgId: orgId,
		updateUser: Engine.profile.nickName
	};

	return requestV2({
		url: 'auditInoutOrder',
		method: 'POST',
		data: param,
		loading: true
	});
}

// 删除待出入库单缓存
export const deletePendingInventoryNetworkCache = () => {
	networkCache.clearByApi('getWaitInoutOrderListByPage');
}


// 获取待入库单详情信息
export const getPendingInventoryDetailInfo = (orgId, id) => {
	const param = {
		"orgId": orgId,
		"waitInoutOrderId": id,
	};

	return requestV2({
		url: 'getWaitInoutOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}


// 获取待入库单列表信息
export const getPendingInventoryData = ({ orgId, pageInfo, filter = null, showLoading = true }) => {
	let param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getWaitInoutOrderListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	});
}

/**
 * 撤销审核并删除单据
 * @param {string} orderId 
 * @param {DocType} orderType 
 * @param {string|null} updateUser 
 * @returns {Promise<ApiReturnStruct>}
 */
export const withdrawReviewAndDeleteOrder = ({
	orderId,
	orderType,
	updateUser = null
}) => {
	_removeOrderCacheForType(orderType.code);

	const param = {
		id: orderId,
		orgId: Engine.profile.org.orgId,
		updateUser: updateUser || Engine.profile?.nickName
	};

	return requestV2({
		url: 'cancleAuditAndDeleteOrder',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		}
	});
};

/**
 * Withdraw review (generic interface)
 * @param {string} orderId 
 * @param {DocType} orderType 
 * @param {string|null} updateUser 
 * @returns {Promise<ApiReturnStruct>}
 */
export const withdrawReview = async ({
	orderId,
	orderType,
	updateUser = null
}) => {
	_removeOrderCacheForType(orderType);

	const param = {
		id: orderId,
		orgId: Engine.profile.org.orgId,
		updateUser: updateUser || Engine.profile?.nickName
	};

	return requestV2({
		url: 'cancleAudit',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		}
	});
};

/**
 * 清除出入库类型缓存
 */
export const deleteInventoryInoutTypeNetworkCache = () => {
	networkCache.clearByApi("getMerchantInoutTypeListByPage");
};

/**
 * 获取入库类型
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter json
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventoryInTypeData = ({ orgId, pageInfo, filter = null, showLoading = true }) => {
	const param = {
		orgId: orgId,
		ign_pullDefAndSelf: 1,
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantInoutTypeListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	});
};

/**
 * 创建出入库类型
 * @param {string} orgId - Organization ID
 * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
 * @param {InventoryInOutType} inoutType - In/out type enum
 * @returns {Promise<ApiReturnStruct>}
 */
export const createInventoryType = ({ orgId, inventoryType, inoutType }) => {
	deleteInventoryInoutTypeNetworkCache();

	const param = {
		orgId: orgId,
		typeCode: inventoryType.code,
		typeName: inventoryType.name,
		typeSource: inoutType === InventoryInOutType.In ? "1" : "0"
	};

	return requestV2({
		url: 'addMerchantInoutTypes',
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 修改出入库类型
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
 * @param {InventoryInOutType} options.inoutType - In/out type enum
 * @returns {Promise<ApiReturnStruct>}
 */
export const editInventoryType = ({
	orgId,
	inventoryType,
	inoutType
}) => {
	deleteInventoryInoutTypeNetworkCache();

	const param = {
		orgId: orgId,
		id: inventoryType.id,
		typeCode: inventoryType.code,
		typeName: inventoryType.name,
		typeSource: inoutType === InventoryInOutType.In ? "1" : "0"
	};

	return requestV2({
		url: 'modMerchantInoutType',
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 删除出入库类型
 * @param {Object} options
 * @param {string} options.typeId - Type ID to delete
 * @param {string} options.orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const delInventoryType = ({ typeId, orgId }) => {
	deleteInventoryInoutTypeNetworkCache();

	return requestV2({
		url: 'delMerchantInoutType',
		method: 'POST',
		data: {
			merchantInoutTypeIds: typeId,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

////////////////////// 库存接口
/**
 * 删除商品库存数量缓存
 */
export const deleteSubCommoditySumDataCache = () => {
	networkCache.clearByApi('getCommondityStorageStoreInfoPage');
	networkCache.clearByApi('getStorageStoreInfoPage');
};

/**
 * 获取商品库存信息
 * @param {string} orgId - Organization ID
 * @param {Object} pageInfo - Pagination info {limitPerPage: number, curIndex: number}
 * @param {Object} [filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getSubCommodityInventorySumData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = {
		orgId: orgId
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
		...param
	};

	// console.log("getSubCommodityInventorySumData getStorageStoreInfoPage param:", paramData);

	return requestV2({
		url: 'getStorageStoreInfoPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
};

/**
 * 获取商品库存信息
 * @param {string} orgId - Organization ID
 * @param {Object} pageInfo - Pagination info {limitPerPage: number, curIndex: number}
 * @param {Object} [filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getSubCommodityInventorySumDataV2 = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = {
		orgId: orgId
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
		...param
	};

	//console.log("getSubCommodityInventorySumDataV2 getCommondityStorageStoreInfoPage param:", paramData);

	return requestV2({
		url: 'getCommondityStorageStoreInfoPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	})
};

//////////////  组装拆卸 Begin   ///////////////////
/**
 * 删除组装拆卸单缓存
 */
export const deleteInventoryAssemblerNetworkCache = () => {
	networkCache.clearByApi("getMerchantAssembleOrderListByPage");
};

/**
 * 获取组装拆卸单列表
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {boolean} [options.showLoading=true] - Show loading indicator
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventoryAssemblerData = ({
	orgId,
	pageInfo,
	filter = null,
	showLoading = true
}) => {
	let param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantAssembleOrderListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	});
};

/**
 * 获取组装拆卸单详情
 * @param {string} id - Order ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventoryAssemblerDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantAssembleOrderId": id,
	};

	return requestV2({
		url: 'getMerchantAssembleOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

/**
 * 创建或更新组装拆卸单
 * @param {InventoryAssembler} inventoryAssembler - Inventory assembler data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateInventoryAssembler = (inventoryAssembler, toAudit) => {
	deleteInventoryAssemblerNetworkCache();
	deleteSubCommoditySumDataCache();
	const api = Util.isEmpty(inventoryAssembler.id)
		? 'addMerchantAssembleOrders'
		: 'modMerchantAssembleOrder';

	const param = inventoryAssembler.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 审核组装拆卸单
 * @param {string} idList - Comma-separated order IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const reviewInventoryAssembler = (idList, orgId) => {
	deleteInventoryAssemblerNetworkCache();
	deleteSubCommoditySumDataCache();
	const param = {
		ids: idList,
		orgId: orgId,
		updateUser: Engine.profile.nickName,
		updateUserId: Engine.profile.id,
	};

	return requestV2({
		url: 'auditAssembleOrder',
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 删除组装拆卸单
 * @param {string} idList - Comma-separated order IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const removeInventoryAssembler = (idList, orgId) => {
	deleteInventoryAssemblerNetworkCache();
	deleteSubCommoditySumDataCache();
	return requestV2({
		url: 'delMerchantAssembleOrder',
		method: 'POST',
		data: {
			merchantAssembleOrderIds: idList,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

//////////////  组装拆卸 End   ///////////////////


//////////////  盘点单 Begin   ///////////////////
/**
 * 删除盘点单缓存
 */
export const deleteInventorySheetNetworkCache = () => {
	networkCache.clearByApi("getMerchantInventoryOrderListByPage");
};

/**
 * 获取盘点单列表
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {boolean} [options.showLoading=true] - Show loading indicator
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventorySheetData = ({
	orgId,
	pageInfo,
	filter = null,
	showLoading = true
}) => {
	let param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantInventoryOrderListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	});
};

/**
 * 创建或更新盘点单
 * @param {InventorySheet} inventorySheet - Inventory sheet data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateInventorySheet = (inventorySheet, toAudit) => {
	deleteInventorySheetNetworkCache();
	deleteSubCommoditySumDataCache();

	const api = Util.isEmpty(inventorySheet.id)
		? 'addMerchantInventoryOrders'
		: 'modMerchantInventoryOrder';

	const param = inventorySheet.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 直接更新商品库存
 * @param {InventorySheet} inventorySheet - Inventory sheet data
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateCommodityInventorySheetShortCut = (inventorySheet) => {
	deleteInventorySheetNetworkCache();
	deleteSubCommoditySumDataCache();

	const param = inventorySheet.toJson();

	return requestV2({
		url: "setMerchantInventory",
		method: 'POST',
		data: param,
		loading: true
	});
};



/**
 * 审核盘点单
 * @param {string} id - Order ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const reviewInventorySheet = (id, orgId) => {
	deleteInventorySheetNetworkCache();
	deleteSubCommoditySumDataCache();

	const param = {
		id: id,
		orgId: orgId,
		updateUser: Engine.profile.nickName,
		updateUserId: Engine.profile.id,
	};

	return requestV2({
		url: 'auditInventoryOrder',
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * 获取盘点单详情
 * @param {string} id - Order ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventorySheetDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantInventoryOrderId": id,
	};

	return requestV2({
		url: 'getMerchantInventoryOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

/**
 * 删除盘点单
 * @param {string} idList - Comma-separated order IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const removeInventorySheet = (idList, orgId) => {
	deleteInventorySheetNetworkCache();

	return requestV2({
		url: 'delMerchantInventoryOrder',
		method: 'POST',
		data: {
			merchantInventoryOrderIds: idList,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};
//////////////  盘点单 End   ///////////////////


//////////////  出入库明细 Begin   ///////////////////
/**
 * 删除出入库明细缓存
 */
export const deleteInventoryInOutRecordNetworkCache = () => {
	networkCache.clearByApi('getStorageInoutOptionInfoListByPage');
};

/**
 * 获取商品信息
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getInventoryInOutRecordData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = {
		orgId: orgId
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
		...param
	};

	console.log("getInventoryInOutRecordData getStorageInoutOptionInfoListByPage param:", paramData);

	return requestV2({
		url: 'getStorageInoutOptionInfoListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
};

//////////////  出入库明细 End   ///////////////////
//////////////  销售单 Begin   ///////////////////
///////////////////////////  销售相关接口
/// 获取销售单详情
export const getSalesDetailInfo = (id, orgId) => {
	const param = {
		orgId: orgId,
		orderId: id,
	};

	return requestV2({
		url: 'getSalesSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}

/*
/// 获取销售单数据（导出）
export const exportSalesContractData = ({ orgId, filter = null }) => {
	const param = { orgId: orgId };

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'exportSales',
		method: 'POST',
		data: param,
		loading: true
	});
}
*/

/// 获取销售单数据（带文件下载）
export const exportSalesContractDataWithDownload = ({ orgId, pageInfo, filter = null, fileFullPath }) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	// TODO: 实现文件下载逻辑，参考 uploadImgFile 方法
	// 在uniapp中可使用 uni.downloadFile 实现下载功能
	console.log("exportSalesContractData exportSales param:", paramData);

	// 这里需要根据实际需求实现下载逻辑
	return requestV2({
		url: 'exportSales',
		method: 'GET', // 根据实际情况可能需要调整为 POST
		data: paramData,
		loading: true
	});
}

/// 删除销售单缓存
export const deleteSalesContractNetworkCache = () => {
	networkCache.clearByApi('getSalesListByPage');
	networkCache.clearByApi('getSalesCommodityListByPage');
}

/// 获取销售单数据
export const getSalesContractData = ({ orgId, pageInfo, filter = null }) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getSalesListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

/// 新建或更新销售单信息
export const updateOrCreateSalesContract = (salesContract, toAudit) => {
	deleteSalesContractNetworkCache();
	deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
	deleteSubCommoditySumDataCache();  //可能影响库存
	// 新增销售单可能是报价单下推单据，更新缓存
	// deleteSalesQuotationNetworkCache(); // 需要确认是否有此方法
	// 删除对账单缓存
	// deleteFundStatementRecordDataNetworkCache(); // 需要确认是否有此方法

	const api = Util.isEmpty(salesContract.id) ? "addSaless" : "modSales";
	const param = salesContract.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
}

/// 审核销售单记录
export const reviewSalesOrder = (ids, orgId) => {
	deleteSalesContractNetworkCache();
	deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
	deleteSubCommoditySumDataCache();  //可能影响库存
	const param = {
		ids: ids,
		orgId: orgId,
		updateUser: Engine.profile.nickName
	};

	return requestV2({
		url: 'audit',
		method: 'POST',
		data: param,
		loading: true
	});
}

/// 删除销售单
export const removeSalesOrder = (idList) => {
	deleteSalesContractNetworkCache();
	// 删除销售单可能是报价单下推单据，更新缓存
	// deleteSalesQuotationNetworkCache(); // 需要确认是否有此方法

	return requestV2({
		url: 'delSales',
		method: 'POST',
		data: {
			orderIds: idList
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}


/**
 * 获取销售单商品列表（拉通查询）
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getSalesContractCommoditiesListData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = { ign_orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getSalesCommodityListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

//////////////  销售单 End   ///////////////////

//////////////  采购单 Begin   ///////////////////
/**
 * 删除采购单缓存
 */
export const deletePurchaseNetworkCache = () => {
	networkCache.clearByApi('getMerchantPurchaseOrderListByPage');
	networkCache.clearByApi('getPurchaseDetailInfoListByPage');    // 采购单详情
}

/**
 * 获取采购单详情
 * @param {string} id - Order ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getPurchaseDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantPurchaseOrderId": id,
	};

	return requestV2({
		url: 'getMerchantPurchaseOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}

/**
 * 导出采购单数据（带文件下载）
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {string} options.fileFullPath - File path for download
 * @returns {Promise<ApiReturnStruct>}
 */
export const exportPurchaseContractDataWithDownload = ({
	orgId,
	pageInfo,
	filter = null,
	fileFullPath
}) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	// TODO: 实现文件下载逻辑，参考 uploadImgFile 方法
	// 在uniapp中可使用 uni.downloadFile 实现下载功能
	console.log("exportPurchaseContractData exportPurchase param:", paramData);

	// 这里需要根据实际需求实现下载逻辑
	return requestV2({
		url: 'exportPurchase',
		method: 'GET', // 根据实际情况可能需要调整为 POST
		data: paramData,
		loading: true
	});
}



/**
 * 获取采购单数据
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getPurchaseContractData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getMerchantPurchaseOrderListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

/**
 * 新建或更新采购单信息
 * @param {PurchaseContract} purchaseContract - Purchase contract data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreatePurchaseContract = (purchaseContract, toAudit) => {
	deletePurchaseNetworkCache();
	deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
	deleteSubCommoditySumDataCache();  //可能影响库存

	const api = Util.isEmpty(purchaseContract.id)
		? "addMerchantPurchaseOrders"
		: "modMerchantPurchaseOrder";

	const param = purchaseContract.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
}

/**
 * 审核采购记录
 * @param {string} ids - Comma-separated order IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const reviewPurchaseOrder = (ids, orgId) => {
	deletePurchaseNetworkCache();
	deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
	deleteSubCommoditySumDataCache();  //可能影响库存

	const param = {
		ids: ids,
		orgId: orgId,
		updateUser: Engine.profile.nickName
	};

	return requestV2({
		url: 'auditPurchaseOrder',
		method: 'POST',
		data: param,
		loading: true
	});
}

/**
 * 删除采购单
 * @param {string} idList - Comma-separated order IDs
 * @returns {Promise<ApiReturnStruct>}
 */
export const removePurchaseOrder = (idList) => {
	deletePurchaseNetworkCache();

	return requestV2({
		url: 'delMerchantPurchaseOrder',
		method: 'POST',
		data: {
			merchantPurchaseOrderIds: idList
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}

/**
 * 获取采购单商品数据 （拉通查询）
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getPurchaseContractDetailData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const param = { ign_orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getPurchaseDetailInfoListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

//////////////  采购单 End   ///////////////////



//////////////  资金账户 Begin   ///////////////////

/**
 * 删除资金账户列表缓存
 */
export const deleteFundAccountListNetworkCacheData = () => {
	networkCache.clearByApi('getMerchantWalletInfoListByPage');
};

/**
 * 资金账户列表接口
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getFundAccountListData = ({
	orgId,
	pageInfo,
	filter = null
}) => {
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
		belongerId: orgId,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			paramData[key] = value;
		}
	}

	// console.log("getFundAccountListData getMerchantWalletInfoListByPage param:", paramData);

	return requestV2({
		url: 'getMerchantWalletInfoListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
};

/**
 * Create or update fund account
 * @param {FundAccount} fundAccount - Fund account data
 * @param {string} token - Authentication token
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateFundAccount = (fundAccount, orgId) => {
	// Clear cache on create/update
	deleteFundAccountListNetworkCacheData();

	const api = !fundAccount.id || fundAccount.id === ""
		? "addMerchantWalletInfos"
		: "modMerchantWalletInfo";

	const param = fundAccount.toJson();
	param["orgId"] = orgId;

	console.log("updateOrCreateFundAccount", api, "param:", param);

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	});
};

/**
 * Get fund account detail info
 * @param {Object} options
 * @param {string} options.token - Authentication token
 * @param {string} options.orgId - Organization ID
 * @param {string} options.id - Account ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getFundAccountDetailInfo = ({ orgId, id }) => {
	const param = {
		"orgId": orgId,
		"merchantWalletInfoId": id,
	};

	console.log("getFundAccountDetailInfo getMerchantWalletInfoSingleById param:", param);

	return requestV2({
		url: 'getMerchantWalletInfoSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
};

/**
 * Remove fund account
 * @param {string} idList - Comma-separated account IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const removeFundAccount = (idList, orgId) => {
	// Clear cache on delete
	deleteFundAccountListNetworkCacheData();

	console.log("removeFundAccount delMerchantWalletInfo param:", idList);

	return requestV2({
		url: 'delMerchantWalletInfo',
		method: 'POST',
		data: {
			merchantWalletInfoIds: idList,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

//////////////  资金账户 End  ///////////////////

////////////// 收款和应收 Begin /////////////////
/// 删除收款单缓存
export const deleteReceiveOrderNetworkCacheData = () => {
	networkCache.clearByApi('getMerchantReceiptOrderListByPage');
}

/// 获取收款单据信息
export const getReceiveOrderData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getMerchantReceiptOrderListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
}

/// 获取收款单详情
export const getReceiveOrderDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantReceiptOrderId": id,
	};

	return requestV2({
		url: 'getMerchantReceiptOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true,
	});
}

/// 创建或更新收款单
export const updateOrCreateReceiveOrder = (receiveOrder, toAudit) => {
	deleteReceiveOrderNetworkCacheData();
	deleteAllTargetObjectPendingReceiveNetworkCacheData();
	deleteTargetObjectPendingReceiveOrderDataNetworkCache();
	// Assuming these methods exist or need to be implemented
	// deleteFundAccountListNetworkCacheData();
	// deleteFundStatementRecordDataNetworkCache();

	const api = !receiveOrder.id || receiveOrder.id === ""
		? "addMerchantReceiptOrders"
		: "modMerchantReceiptOrder";

	const param = receiveOrder.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true,
	});
}

/// 审核收款单记录
export const reviewReceiveOrder = (ids, orgId) => {
	deleteReceiveOrderNetworkCacheData();
	deleteAllTargetObjectPendingReceiveNetworkCacheData();
	deleteTargetObjectPendingReceiveOrderDataNetworkCache();
	// Assuming these methods exist or need to be implemented
	// deleteFundAccountListNetworkCacheData();

	const param = {
		'ids': ids,
		'orgId': orgId,
		"updateUser": Engine.profile.nickName
	};

	return requestV2({
		url: 'auditReceiptOrder',
		method: 'POST',
		data: param,
		loading: true,
	});
}

/// 删除收款单
export const removeReceiveOrder = (idList) => {
	deleteReceiveOrderNetworkCacheData();
	deleteAllTargetObjectPendingReceiveNetworkCacheData();
	deleteTargetObjectPendingReceiveOrderDataNetworkCache();
	// Assuming these methods exist or need to be implemented
	// deleteFundAccountListNetworkCacheData();
	// deleteFundStatementRecordDataNetworkCache();

	return requestV2({
		url: 'delMerchantReceiptOrder',
		method: 'POST',
		data: {
			'merchantReceiptOrderIds': idList
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true,
	});
}

/// 删除应付单缓存
export const deleteTargetObjectPendingReceiveOrderDataNetworkCache = () => {
	networkCache.clearByApi('getWaitReceiptOrderListByPage');
}

/// 单个对象应收款资金单据信息
export const getTargetObjectPendingReceiveOrderData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getWaitReceiptOrderListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
}

/// 获取应付单详情
export const getPendingReceiveOrderDetailInfo = (orgId, id) => {
	const param = {
		"orgId": orgId,
		"waitReceiptOrderId": id,
	};

	return requestV2({
		url: 'getWaitReceiptOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true,
	});
}


////////////// 收款和应收 End   /////////////////

////////////// 付款和应付 Begin   /////////////////

////////////// 付款和应付 Begin /////////////////

/// 删除应付单缓存
export const deleteTargetObjectPendingPaymentOrderDataNetworkCache = () => {
	networkCache.clearByApi('getWaitPaymentOrderListByPage');
}

/// 单个对象待支付资金单据信息
export const getTargetObjectPendingPaymentOrderData = ({ orgId, pageInfo, filter = null }) => {
	const param = {
		"orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex,
	};

	if (filter != null) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}

	return requestV2({
		url: 'getWaitPaymentOrderListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
}

/// 获取应付单详情
export const getPendingPaymentOrderDetailInfo = (orgId, id) => {
	const param = {
		"orgId": orgId,
		"waitPaymentOrderId": id,
	};

	return requestV2({
		url: 'getWaitPaymentOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true,
	});
}

/// 删除付款单缓存
export const deletePaymentOrderNetworkCacheData = () => {
	networkCache.clearByApi('getMerchantPaymentOrderListByPage');
}

/// 获取支付的资金单据信息
export const getPaymentOrderData = ({ orgId, pageInfo, filter = null }) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getMerchantPaymentOrderListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

/// 创建或更新付款单
export const updateOrCreatePaymentOrder = (paymentOrder, toAudit) => {
	// Assuming these cache clearing functions exist
	// deleteFundRecordDataNetworkCache();
	deletePaymentOrderNetworkCacheData();
	deleteAllTargetObjectPendingPaymentNetworkCacheData();
	deleteTargetObjectPendingPaymentOrderDataNetworkCache();
	deleteFundAccountListNetworkCacheData();
	// deleteFundStatementRecordDataNetworkCache();

	const api = !paymentOrder.id || paymentOrder.id === ""
		? "addMerchantPaymentOrders"
		: "modMerchantPaymentOrder";

	const param = paymentOrder.toJson();
	param['toAudit'] = toAudit ? 1 : 0;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true,
	});
}

/// 获取付款单详情
export const getPaymentOrderDetailInfo = (orgId, id) => {
	const param = {
		"orgId": orgId,
		"merchantPaymentOrderId": id,
	};

	return requestV2({
		url: 'getMerchantPaymentOrderSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}

/// 审核付款单记录
export const reviewPaymentOrder = (ids, orgId) => {
	deletePaymentOrderNetworkCacheData();
	deleteAllTargetObjectPendingPaymentNetworkCacheData();
	deleteTargetObjectPendingPaymentOrderDataNetworkCache();
	deleteFundAccountListNetworkCacheData();
	// deleteFundStatementRecordDataNetworkCache();

	const param = {
		'ids': ids,
		'orgId': orgId,
		"updateUser": Engine.profile.nickName
	};

	return requestV2({
		url: 'auditPaymentOrder',
		method: 'POST',
		data: param,
		loading: true,
	});
}

/// 删除付款单
export const removePaymentOrder = (idList) => {
	deletePaymentOrderNetworkCacheData();
	deleteAllTargetObjectPendingPaymentNetworkCacheData();
	deleteTargetObjectPendingPaymentOrderDataNetworkCache();
	deleteFundAccountListNetworkCacheData();
	// deleteFundStatementRecordDataNetworkCache();

	return requestV2({
		url: 'delMerchantPaymentOrder',
		method: 'POST',
		data: {
			'merchantPaymentOrderIds': idList
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true,
	});
}

////////////// 付款和应付 End   /////////////////

////////////// 自定义支付类型 Begin   /////////////////
/// 删除付款单缓存
export const deleteSelfAccountTypeNetworkCacheData = () => {
	networkCache.clearByApi('getMerchantSelfAccountTypeListByPage');
}
/// 获取自定义账户类型
export const getSelfFundAccountType = ({ orgId, pageInfo, filter = null, showLoading = false }) => {
	let param = {
		"orgId": orgId,
	};
	// 合并 filter
	if (filter && Object.keys(filter).length > 0) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}
	// 分页参数
	param['pageSize'] = pageInfo.limitPerPage;
	param['pageNum'] = pageInfo.curIndex;

	return requestV2({
		url: 'getMerchantSelfAccountTypeListByPage',
		method: 'GET',
		data: param,
		loading: showLoading,
		enableCache: true
	})
}

/// 创建自定义账户类型
export const createSelfFundAccountType = (name, code, orgId) => {
	deleteSelfAccountTypeNetworkCacheData();
	let param = {
		'orgId': orgId,
		'name': name,
		'code': code,
	}
	return requestV2({
		url: 'addMerchantSelfAccountType',
		method: 'POST',
		data: param,
		loading: true,
	})
}

/// 修改自定义账户类型
export const updateSelfFundAccountType = (id, name, code, orgId) => {
	deleteSelfAccountTypeNetworkCacheData();
	let param = {
		'orgId': orgId,
		'id': id,
		'name': name,
		'code': code,
	}
	return requestV2({
		url: 'modMerchantSelfAccountType',
		method: 'POST',
		data: param,
		loading: true,
	})
}

/// 删除自定义账户类型
export const delSelfFundAccountType = (categoryId, orgId) => {
	deleteSelfAccountTypeNetworkCacheData();
	let param = {
		'accountTypeIds': categoryId,
		'orgId': orgId
	}
	return requestV2({
		url: 'delMerchantSelfAccountType',
		method: 'POST',
		data: param,
		loading: true,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	})
}

////////////// 自定义支付类型 End   /////////////////


////////////// 往来其他费用类型 Begin   /////////////////

/**
 * 删除往来其他费用类型缓存
 */
export const deleteOtherFeeTypeNetworkCache = () => {
    networkCache.clearByApi('getMerchantOtherFeeTypeListByPage');
}

/**
 * 获取往来其他费用类型
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {boolean} [options.showLoading=false] - Show loading indicator
 * @returns {Promise<ApiReturnStruct>}
 */
export const getOtherFeeTypeData = ({ orgId, pageInfo, filter = null, showLoading = false }) => {
    let param = {
        "orgId": orgId,
    };
    
    // 合并 filter
    if (filter && Object.keys(filter).length > 0) {
        for (let [key, value] of Object.entries(filter)) {
            param[key] = value;
        }
    }
    
    // 分页参数
    param['pageSize'] = pageInfo.limitPerPage;
    param['pageNum'] = pageInfo.curIndex;

    return requestV2({
        url: 'getMerchantOtherFeeTypeListByPage',
        method: 'GET',
        data: param,
        loading: showLoading,
		enableCache: true
    })
}

/**
 * 创建往来其他费用类型
 * @param {string} name - 费用类型名称
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const createOtherFeeType = (name, code, orgId) => {
    deleteOtherFeeTypeNetworkCache();
    let param = {
        'orgId': orgId,
        'name': name
    }

	if(code)
	{
		param['code'] = code;
	}
    
    return requestV2({
        url: 'addMerchantOtherFeeType',
        method: 'POST',
        data: param,
        loading: true,
    })
}

/**
 * 修改往来其他费用类型
 * @param {string} id - 费用类型ID
 * @param {string} name - 费用类型名称
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOtherFeeType = ({id, name, code, orgId}) => {
    deleteOtherFeeTypeNetworkCache();
    let param = {
        'orgId': orgId,
        'id': id,		
        'name': name
    }

	if(code)
	{
		param['code'] = code;
	}
    
    return requestV2({
        url: 'modMerchantOtherFeeType',
        method: 'POST',
        data: param,
        loading: true,
    })
}

/**
 * 删除往来其他费用类型
 * @param {string} typeId - 费用类型ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const delOtherFeeType = (typeId, orgId) => {
    deleteOtherFeeTypeNetworkCache();
    let param = {
        'merchantOtherFeeTypeIds': typeId,
        'orgId': orgId
    }
    
    return requestV2({
        url: 'delMerchantOtherFeeType',
        method: 'POST',
        data: param,
        loading: true,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    })
}

////////////// 往来其他费用类型 End   /////////////////

//////////////  委外加工提纯 Begin   ///////////////////
/**
 * 删除委外加工单缓存
 */
export const deleteMetalRefiningContractNetworkCache = () => {
    networkCache.clearByApi('getMerchantMetalRefiningOrderListByPage');
	
}

/**
 * 获取委外加工单详情
 * @param {string} id - Order ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getMetalRefiningDetailInfo = (id, orgId) => {
    const param = {
        "orgId": orgId,
        "merchantMetalRefiningOrderId": id,
    };

    return requestV2({
        url: 'getMerchantMetalRefiningOrderSingleById',
        method: 'POST',
        data: param,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        loading: true
    });
}

/**
 * 导出委外加工单数据（带文件下载）
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {string} options.fileFullPath - File path for download
 * @returns {Promise<ApiReturnStruct>}
 */
export const exportMetalRefiningContractDataWithDownload = ({
    orgId,
    pageInfo,
    filter = null,
    fileFullPath
}) => {
    const param = { orgId: orgId };
    const paramData = {
        pageSize: pageInfo.limitPerPage,
        pageNum: pageInfo.curIndex,
    };

    if (filter) {
        for (const [key, value] of Object.entries(filter)) {
            // 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
            // 暂时将所有参数都添加到 paramData 中
            paramData[key] = value;
        }
    }

    for (const [key, value] of Object.entries(param)) {
        paramData[key] = value;
    }

    // TODO: 实现文件下载逻辑，参考 uploadImgFile 方法
    // 在uniapp中可使用 uni.downloadFile 实现下载功能
    console.log("exportMetalRefiningContractData exportMetalRefine param:", paramData);

    // 这里需要根据实际需求实现下载逻辑
    return requestV2({
        url: 'exportRefining',
        method: 'GET', // 根据实际情况可能需要调整为 POST
        data: paramData,
        loading: true
    });
}

/**
 * 获取委外加工单数据
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getMetalRefiningContractData = ({
    orgId,
    pageInfo,
    filter = null
}) => {
    const param = { orgId: orgId };
    const paramData = {
        pageSize: pageInfo.limitPerPage,
        pageNum: pageInfo.curIndex,
    };

    if (filter) {
        for (const [key, value] of Object.entries(filter)) {
            // 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
            // 暂时将所有参数都添加到 paramData 中
            paramData[key] = value;
        }
    }

    for (const [key, value] of Object.entries(param)) {
        paramData[key] = value;
    }

    return requestV2({
        url: 'getMerchantMetalRefiningOrderListByPage',
        method: 'GET',
        data: paramData,
        enableCache: true
    });
}

/**
 * 新建或更新委外加工单信息
 * @param {MetalRefiningContract} contract - Metal refining contract data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateMetalRefiningContract = (contract, toAudit) => {
    deleteMetalRefiningContractNetworkCache();
    deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
    deleteSubCommoditySumDataCache();  //可能影响库存

    const api = Util.isEmpty(contract.id)
        ? "addMerchantMetalRefiningOrder"
        : "modMerchantMetalRefiningOrder";

    const param = contract.toJson();
    param['toAudit'] = toAudit ? 1 : 0;

    return requestV2({
        url: api,
        method: 'POST',
        data: param,
        loading: true
    });
}

/**
 * 审核委外加工单记录
 * @param {string} ids - Comma-separated order IDs
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const reviewMetalRefiningOrder = (ids, orgId) => {
    deleteMetalRefiningContractNetworkCache();
    deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
    deleteSubCommoditySumDataCache();  //可能影响库存
	deleteFundAccountListNetworkCacheData(); // 清除资金账户缓存

    const param = {
        ids: ids,
        orgId: orgId,
        updateUser: Engine.profile.nickName
    };

    return requestV2({
        url: 'auditRefiningOrder',
        method: 'POST',
        data: param,
        loading: true
    });
}




//////////////  委外加工提纯 End   ///////////////////


//////////////  贵金属业务单 Start   ///////////////////
/// 删除销售单缓存
export const deleteMetalCombineOrderNetworkCache = () => {
	networkCache.clearByApi('getMerchantCustomerMetalCombineOrderListByPage');	
}

/// 获取销售单数据
export const getMetalCombineData = ({ orgId, pageInfo, filter = null }) => {
	const param = { orgId: orgId };
	const paramData = {
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};

	if (filter) {
		for (const [key, value] of Object.entries(filter)) {
			// 注意：这里需要根据实际业务逻辑判断 isParamFilter(key)
			// 暂时将所有参数都添加到 paramData 中
			paramData[key] = value;
		}
	}

	for (const [key, value] of Object.entries(param)) {
		paramData[key] = value;
	}

	return requestV2({
		url: 'getMerchantCustomerMetalCombineOrderListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

/**
 * 新建或更新 贵金属业务单
 * @param {MetalRefiningContract} contract - Metal refining contract data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateMetalCombineOrder = (contract) => {
    deleteMetalCombineOrderNetworkCache();
    deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
    deleteSubCommoditySumDataCache();  //可能影响库存
	deleteFundAccountListNetworkCacheData(); // 清除资金账户缓存
	

    const api = Util.isEmpty(contract.id)
        ? "addMerchantCustomerMetalCombineOrder"
        : "modMerchantCustomerMetalCombineOrder";

    const param = contract.toJson();

    return requestV2({
        url: api,
        method: 'POST',
        data: param,
        loading: true
    });
}

/**
 * 批量新建或更新 贵金属业务单
 * @param {MetalRefiningContract} contract - Metal refining contract data
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateMetalCombineOrderBatch = ({param,orgId}) => {
    deleteMetalCombineOrderNetworkCache();
    deleteInventoryInOutRecordNetworkCache();  // 可能会有出入库单
    deleteSubCommoditySumDataCache();  //可能影响库存
	deleteFundAccountListNetworkCacheData(); // 清除资金账户缓存
	

    const api = "updateMetalCombineOrderBatch";

	param.orgId = orgId;

    return requestV2({
        url: api,
        method: 'POST',
        data: param,
        loading: true
    });
}

//////////////  贵金属业务单 End   ///////////////////


//////////////  结算单 Star   ///////////////////
export const deletePeriodSettleNetworkCache = () => {
	networkCache.clearByApi('getMerchantPeriodSettlementOrderListByPage');	
}

/// 获取销售单数据
export const getPeriodSettleData = ({ orgId, pageInfo, filter = null }) => {
	
	const paramData = {
		...filter,
		orgId: orgId,
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};


	return requestV2({
		url: 'getMerchantPeriodSettlementOrderListByPage',
		method: 'GET',
		data: paramData,
		enableCache: true
	});
}

/**
 * 发起混合单据期末结算
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {PeriodSettlementOrder} settleOrder
 * @returns {Promise<ApiReturnStruct>}
 */
export const settleCombineOrder = ({ settleOrder, orgId  }) => {
	// 增删改清除缓存
	deleteMetalCombineOrderNetworkCache();
	deletePeriodSettleNetworkCache();

	const api = "settleCombineOrder";

	const param = settleOrder.toJson();
	param["orgId"] = orgId;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	})
}

/**
 * 删除混合单据期末结算
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {PeriodSettlementOrder} settleOrder
 * @returns {Promise<ApiReturnStruct>}
 */
export const removeSettleCombineOrder = ({ settleOrder, orgId  }) => {
	// 增删改清除缓存
	deleteMetalCombineOrderNetworkCache();
	deletePeriodSettleNetworkCache();

	const api = "removeSettleCombineOrder";

	const param = settleOrder.toJson();
	param["orgId"] = orgId;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	})
}
//////////////  结算单 End   ///////////////////

//////////////  贵金属客户结算列表 Star   ///////////////////
export const deleteCustomersMetalBalanceNetworkCache = () => {
	networkCache.clearByApi('getCustomersMetalBalanceByPage');	
}

/// 获取销售单数据
export const getCustomersMetalBalanceData = ({ orgId, pageInfo, filter = null }) => {
	
	const paramData = {
		...filter,
		orgId: orgId,
		pageSize: pageInfo.limitPerPage,
		pageNum: pageInfo.curIndex,
	};


	return requestV2({
		url: 'getCustomersMetalBalanceByPage',
		method: 'GET',
		data: paramData,
		enableCache: false
	});
}
//////////////  贵金属客户结算列表 End   ///////////////////

//////////////  角色管理 Start   ///////////////////
/// 清除角色数据缓存
export const deleteRoleDataNetworkCache = () => {
	networkCache.clearByApi('getMerchantRoleInfoListByPage');
}

/**
 * 获取角色信息
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getRoleData = ({ orgId, pageInfo, filter = null }) => {
	let param = {
		"orgId": orgId,
		...filter
	};

	// 分页参数
	param['pageSize'] = pageInfo.limitPerPage;
	param['pageNum'] = pageInfo.curIndex;

	return requestV2({
		url: 'getMerchantRoleInfoListByPage',
		method: 'GET',
		data: param,
		loading: false,
		enableCache: true
	})
}

/**
 * 删除角色接口
 * @param {Object} options
 * @param {string} options.roleId - Role ID to delete
 * @param {string} options.orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const delRole = ({ roleId, orgId }) => {
	// 增删改清除缓存
	deleteRoleDataNetworkCache();

	return requestV2({
		url: 'delMerchantRoleInfo',
		method: 'POST',
		data: {
			merchantRoleInfoIds: roleId,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
}

/**
 * 获取角色详情
 * @param {string} id - Role ID
 * @param {string} orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const getRoleDetailInfo = (id, orgId) => {
	const param = {
		"orgId": orgId,
		"merchantRoleInfoId": id,
	};

	return requestV2({
		url: 'getMerchantRoleInfoSingleById',
		method: 'POST',
		data: param,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		loading: true
	});
}

/**
 * 创建或更新角色数据
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {Role} options.role - Role data
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateRoleData = ({ role, orgId  }) => {
	// 增删改清除缓存
	deleteRoleDataNetworkCache();

	const api = Util.isEmpty(role.id)
		? "addMerchantRoleInfos"
		: "modMerchantRoleInfo";

	const param = role.toJson();
	param["orgId"] = orgId;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	})
}
//////////////  角色管理 End   ///////////////////


//////////////  员工管理 End   ///////////////////

//////////////  首页统计 start   ///////////////////
/// 删除获取统计当日，昨日，本月营收，贵金属回收销售缓存
export const delCombineOrderInOutStatic = () => {
	networkCache.clearByApi('getCombineOrderInOutStatic');	
}

/// 获取统计当日，昨日，本月营收，贵金属回收销售
export const getCombineOrderInOutStatic = ({ orgId}) => {
	const param = { orgId: orgId };

	return requestV2({
		url: 'getCombineOrderInOutStatic',
		method: 'GET',
		data: param,
		enableCache: true
	});
}

/// 查询当前存欠款和存欠料数据
export const delCurrentPeriodBalance = () => {
	networkCache.clearByApi('getCurrentPeriodBalance');	
}

/// 查询当前存欠款和存欠料数据
export const getCurrentPeriodBalance = ({ orgId}) => {
	const param = { orgId: orgId };

	return requestV2({
		url: 'getCurrentPeriodBalance',
		method: 'GET',
		data: param,
		enableCache: true
	});
}

//////////////  首页统计 End   ///////////////////

/**
 * 清除员工数据缓存
 */
export const deleteEmployeeDataNetworkCache = () => {
	networkCache.clearByApi('getMerchantAccountListByPage');
};

/**
 * 员工列表信息接口
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>}
 */
export const getEmployeeData = ({ orgId, pageInfo, filter = null }) => {
	let param = {
		"b_orgId": orgId,
		"pageSize": pageInfo.limitPerPage,
		"pageNum": pageInfo.curIndex
	};

	if (filter && Object.keys(filter).length > 0) {
		for (let [key, value] of Object.entries(filter)) {
			param[key] = value;
		}
	}


	return requestV2({
		url: 'getMerchantAccountListByPage',
		method: 'GET',
		data: param,
		enableCache: true,
	});
};

/// 获取员工详情信息
export const getEmployeeDetailInfo = (id, orgId) => {
	let param = { 'accountId': id, 'b_orgId': orgId };
	//return request('getMerchantAccountSingle', 'GET', param, false)
	return requestV2({
		url: 'getMerchantAccountSingle',
		method: 'GET',
		data: param,
		loading: false,
	})
}

/**
 * 创建或更新员工数据
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {Employee} options.employee - Employee data
 * @returns {Promise<ApiReturnStruct>}
 */
export const updateOrCreateEmployeeData = ({ orgId, employee }) => {
	// 增删改清除缓存
	deleteEmployeeDataNetworkCache();

	const api = Util.isEmpty(employee.id)
		? "addMerchantChildAccounts"
		: "modMerchantAccount";

	const param = employee.toJson();
	param["orgId"] = orgId;
	param["createOrgId"] = orgId;
	param["rootOrgId"] = orgId;
	param["createUser"] = Engine.profile.id;

	return requestV2({
		url: api,
		method: 'POST',
		data: param,
		loading: true
	})
};

/**
 * 删除员工接口
 * @param {Object} options
 * @param {string} options.employeeId - Employee ID to delete
 * @param {string} options.orgId - Organization ID
 * @returns {Promise<ApiReturnStruct>}
 */
export const delEmployee = ({ employeeId, orgId }) => {
	// 增删改清除缓存
	deleteEmployeeDataNetworkCache();


	return requestV2({
		url: 'delMerchantChildAccount',
		method: 'POST',
		data: {
			merchantAccountIds: employeeId,
			orgId: orgId
		},
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		loading: true
	});
};

//////////////// 员工管理 End ///////////////////


/**
 *根据单据类型删除缓存
 * @param {DocType.code} orderType 
 */
const _removeOrderCacheForType = (orderType) => {
	let removeStatementCache = false;
	let removePaymentRelatedCache = false;
	let removeReceiveRelatedCache = false;
	let removeInventoryRelatedCache = false;

	switch (orderType) {
		case DocType.CGD.code:
			deletePurchaseNetworkCache();
			removeStatementCache = true;
			removePaymentRelatedCache = true;
			removeInventoryRelatedCache = true;
			break;
		case DocType.CGTHD.code:
			//deletePurchaseReturnNetworkCache();
			removeStatementCache = true;
			removePaymentRelatedCache = true;
			removeInventoryRelatedCache = true;
			break;
		case DocType.QUOTATION.code:
			//deleteSalesQuotationNetworkCache();
			break;
		case DocType.XSD.code:
			deleteSalesContractNetworkCache();
			removeStatementCache = true;
			removeReceiveRelatedCache = true;
			removeInventoryRelatedCache = true;
			break;
		case DocType.XSTHD.code:
			//deleteSalesReturnNetworkCache();
			removeStatementCache = true;
			removeReceiveRelatedCache = true;
			removeInventoryRelatedCache = true;
			break;
		case DocType.CKD.code:
		case DocType.RKD.code:
			deleteInventoryNetworkCache();
			removeInventoryRelatedCache = true;
			break;
		case DocType.DBD.code:
			//deleteInventoryTransferNetworkCache();
			removeInventoryRelatedCache = true;
			break;
		case DocType.SKD.code:
			deleteReceiveOrderNetworkCacheData();
			removeStatementCache = true;
			removeReceiveRelatedCache = true;
			break;
		case DocType.FKD.code:
			deletePaymentOrderNetworkCacheData();
			removeStatementCache = true;
			removePaymentRelatedCache = true;
			break;
		case DocType.ZFKD.code:
			//deleteDirectFundDataNetworkCache();
			break;
		case DocType.ZSKD.code:
			//deleteDirectFundDataNetworkCache();
			break;
		case DocType.ASSEMBLER.code:
			deleteInventoryAssemblerNetworkCache();
			removeInventoryRelatedCache = true;
			break;
		case DocType.PDD.code:
			deleteInventorySheetNetworkCache();
			removeInventoryRelatedCache = true;
			break;
		default:
			break;
	}

	if (removeStatementCache) {
		//	deleteFundStatementRecordDataNetworkCache();
	}

	if (removePaymentRelatedCache) {
		//deleteAllTargetObjectPendingPaymentNetworkCacheData();
		//deleteTargetObjectPendingPaymentOrderDataNetworkCache();
		//deleteFundAccountListNetworkCacheData();
		//deleteFundStatementRecordDataNetworkCache();
	}

	if (removeReceiveRelatedCache) {
		deleteAllTargetObjectPendingReceiveNetworkCacheData();
		deleteTargetObjectPendingReceiveOrderDataNetworkCache();
		deleteFundAccountListNetworkCacheData();
		//deleteFundStatementRecordDataNetworkCache();
	}

	if (removeInventoryRelatedCache) {
		deleteSubCommoditySumDataCache();
		// 出入库记录更新
		deleteInventoryInOutRecordNetworkCache();
	}
};


/**
* 上传图片文件 todo 待调试
* @param {string} filePath - 本地文件路径
* @returns {Promise<{data: any, resErr: any}>} - 返回上传结果
*/
export const uploadImgFile = async (filePath) => {
	let token = Engine.profile.token;
	const ret = { data: null, resErr: null };

	if (process.env.NODE_ENV === 'development') {
		console.log("uploadImgFile uploadImage local filePath:", filePath);
	}

	try {
		// 在uniapp中使用uni.uploadFile API
		const uploadResult = await new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${Definition.baseUrlWithoutService}work-file-service/uploadImage`,
				filePath: filePath,
				name: 'file',
				header: {
					'token': token,
					'Content-Type': 'multipart/form-data'
				},
				success: (res) => {
					if (res.statusCode === 200) {
						try {
							// 尝试解析返回数据
							const data = JSON.parse(res.data);
							resolve(data);
						} catch (e) {
							// 如果解析失败，直接返回原始数据
							resolve(res.data);
						}
					} else {
						reject(new Error(`上传失败，状态码: ${res.statusCode}`));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});

		if (process.env.NODE_ENV === 'development') {
			console.log("uploadImgFile uploadImage response:", uploadResult);
		}

		ret.data = uploadResult;
		return ret;
	} catch (e) {
		console.error("request uploadImgFile uploadImage failed:", e.message);
		ret.resErr = e;
		return ret;
	}
}




